package com.example.myapplicationktkt2.camera

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import com.example.myapplicationktkt2.R
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date

/**
 * 创建了 CameraDemoActivity 类，实现了以下功能：
 * 拍照功能：通过调用系统相机应用拍照，并保存到设备存储
 * 选择照片功能：从设备相册中选择已有照片
 * 照片预览：在ImageView中显示拍摄或选择的照片
 * 权限处理：请求相机权限以进行拍照
 * 创建了相应的布局文件 activity_camera_demo.xml，包含：
 * 图片预览区域（ImageView）
 * 拍照和选择照片按钮
 * 信息显示区域
 * 更新了 AndroidManifest.xml 文件：
 * 添加了相机使用权限声明
 * 添加了相机硬件特性声明
 * 注册了 CameraDemoActivity
 * 更新了文件提供者配置
 * 更新了主界面：
 * 在 activity_main.xml 中添加了"相机使用演示"按钮
 * 在 MainActivity.kt 中添加了启动相机演示的代码
 * 功能特点
 * 拍照功能：用户可以点击"拍照"按钮启动系统相机应用进行拍照，照片会自动保存到设备存储中
 * 选择照片功能：用户可以点击"选择照片"按钮从设备相册中选择已有照片
 * 权限处理：在Android 6.0及以上设备中，应用会在需要时请求相机权限
 * 照片预览：拍摄或选择的照片会显示在预览区域
 * 信息提示：显示相关操作的信息和状态
 * 技术实现细节
 * 使用 FileProvider 安全地分享照片文件给相机应用
 * 使用外部存储目录保存拍摄的照片
 * 实现了缩略图加载以提高性能
 * 正确处理了Activity结果回调
 */
class CameraDemoActivity : AppCompatActivity() {

    companion object {
        private const val REQUEST_IMAGE_CAPTURE = 1
        private const val REQUEST_IMAGE_PICK = 2
        private const val REQUEST_CAMERA_PERMISSION = 100
    }

    private lateinit var captureButton: Button
    private lateinit var selectButton: Button
    private lateinit var imageView: ImageView
    private lateinit var infoText: TextView
    private var currentPhotoPath: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_camera_demo)

        initViews()
        setupListeners()
    }

    private fun initViews() {
        captureButton = findViewById(R.id.btn_capture)
        selectButton = findViewById(R.id.btn_select)
        imageView = findViewById(R.id.image_view)
        infoText = findViewById(R.id.text_info)
    }

    private fun setupListeners() {
        captureButton.setOnClickListener {
            if (checkCameraPermission()) {
                dispatchTakePictureIntent()
            } else {
                requestCameraPermission()
            }
        }

        selectButton.setOnClickListener {
            dispatchSelectPictureIntent()
        }
    }

    private fun checkCameraPermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.CAMERA
        ) == PackageManager.PERMISSION_GRANTED
    }

    private fun requestCameraPermission() {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.CAMERA),
            REQUEST_CAMERA_PERMISSION
        )
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            REQUEST_CAMERA_PERMISSION -> {
                if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    dispatchTakePictureIntent()
                } else {
                    Toast.makeText(this, "需要相机权限才能拍照", Toast.LENGTH_SHORT).show()
                }
                return
            }
        }
    }

    private fun dispatchTakePictureIntent() {
        Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
            // 确保有相机应用可以处理intent
            takePictureIntent.resolveActivity(packageManager)?.also {
                // 创建文件存放照片
                val photoFile: File? = try {
                    createImageFile()
                } catch (ex: IOException) {
                    // 错误处理
                    Toast.makeText(this, "创建图片文件失败", Toast.LENGTH_SHORT).show()
                    null
                }
                // 继续执行，仅当文件创建成功时
                photoFile?.also {
                    val photoURI: Uri = FileProvider.getUriForFile(
                        this,
                        "${packageName}.fileprovider",
                        it
                    )
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
                    startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
                }
            }
        }
    }

    private fun dispatchSelectPictureIntent() {
        Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI).also { pickIntent ->
            pickIntent.type = "image/*"
            startActivityForResult(pickIntent, REQUEST_IMAGE_PICK)
        }
    }

    @Throws(IOException::class)
    private fun createImageFile(): File {
        // 创建图片文件名
        val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
        val imageFileName = "JPEG_${timeStamp}_"
        val storageDir: File = getExternalFilesDir(Environment.DIRECTORY_PICTURES)!!
        return File.createTempFile(
            imageFileName,  /* 前缀 */
            ".jpg",         /* 后缀 */
            storageDir      /* 目录 */
        ).apply {
            // 保存文件路径供以后使用
            currentPhotoPath = absolutePath
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            REQUEST_IMAGE_CAPTURE -> {
                if (resultCode == RESULT_OK) {
                    // 显示拍摄的照片
                    setPic()
                    infoText.text = "照片已拍摄并保存到:\n$currentPhotoPath"
                }
            }
            REQUEST_IMAGE_PICK -> {
                if (resultCode == RESULT_OK && data != null) {
                    try {
                        val imageUri: Uri = data.data!!
                        val imageStream = contentResolver.openInputStream(imageUri)
                        val selectedImage = BitmapFactory.decodeStream(imageStream)
                        imageView.setImageBitmap(selectedImage)
                        infoText.text = "已选择照片"
                    } catch (e: Exception) {
                        e.printStackTrace()
                        Toast.makeText(this, "选择照片失败", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }

    private fun setPic() {
        // 获取图片的尺寸
        val targetW = imageView.width
        val targetH = imageView.height

        val bmOptions = BitmapFactory.Options().apply {
            // 获取图片的原始尺寸
            inJustDecodeBounds = true
        }

        BitmapFactory.decodeFile(currentPhotoPath, bmOptions)

        val photoW = bmOptions.outWidth
        val photoH = bmOptions.outHeight

        // 确定缩放比例
        val scaleFactor = Math.min(photoW / targetW, photoH / targetH)

        // 解码图片为缩略图
        bmOptions.apply {
            inJustDecodeBounds = false
            inSampleSize = scaleFactor
        }

        // 解码图片文件
        BitmapFactory.decodeFile(currentPhotoPath, bmOptions)?.also { bitmap ->
            imageView.setImageBitmap(bitmap)
        }
    }
}